package org.wangduqing.ibatisdao.factory;

import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.wangduqing.ibatisdao.anotation.IbatisDao;
import org.wangduqing.ibatisdao.util.IbatisDaoUtil;

public class IbatisDaoBeanFactory implements BeanFactoryPostProcessor {
	
	private static final Logger logger = Logger.getLogger(IbatisDaoBeanFactory.class);
	private List<String> packagesToScan;

	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

		logger.debug("................MiniDaoBeanFactory................ContextRefreshed................begin...................");
        for(String pack:packagesToScan){
        	
        	if(org.apache.commons.lang.StringUtils.isNotEmpty(pack)){
        		
        		Set<Class<?>> classSet = PackagesToScanUtil.getClasses(pack);
        		for(Class<?> ibatisDaoClass:classSet){
        			
        			if(ibatisDaoClass.isAnnotationPresent(IbatisDao.class)){
        				
        				ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
        				proxyFactoryBean.setBeanFactory(beanFactory);
        				proxyFactoryBean.setInterfaces(new Class[] {ibatisDaoClass});
        				proxyFactoryBean.setInterceptorNames(new String[] {"ibatisDaoHandler"});
        				String beanName = IbatisDaoUtil.getFirstSmall(ibatisDaoClass.getSimpleName());
        				if(!beanFactory.containsBean(beanName)){
        					
        					logger.info("IbatisDao Interface [/"+ibatisDaoClass.getName()+"/] onto Spring Bean '"+beanName+"'");
        					beanFactory.registerSingleton(beanName, proxyFactoryBean.getObject());
        					
        				}
        			}
        			
        		}
        	}
        	
        }
        
	}

	public List<String> getPackagesToScan() {
		return packagesToScan;
	}

	public void setPackagesToScan(List<String> packagesToScan) {
		this.packagesToScan = packagesToScan;
	}
	
}
